
import HTTP from '../util/http.js';

class ClassicModel extends HTTP {
    getLatest(cb){   //最后一期
        this.request({
            url: '/classic/latest'
        }).then((res) => {
            cb(res);
            this._setLatest(res.index);
            let key = this._getKey(res.index);
            wx.setStorageSync(key, res);
        });
    };
    getPrevOrNext(index, behavior, cb){   //上一期或者下一期
        let prevOrLeft = behavior === 'prev' ? 'previous' : 'next';
        let _index = behavior === 'prev' ? (index - 1) : (index + 1);
        let key = this._getKey(_index);
        let classicData = wx.getStorageSync(key);
        if (!classicData){
            this.request({
                url: `/classic/${index}/${prevOrLeft}`
            }).then((res) => {
                cb(res);
                wx.setStorageSync(this._getKey(res.index), res);  //数据写入缓存中，从缓存中取，不需要走接口
            });
        }else{
            cb(classicData);
        }
    };
    isFirst(index){
        return index === 1 ? true : false;
    };
    isLatest(index){
        let latestIndex = this._getLatest();
        return index === latestIndex ? true : false;
    };
    _setLatest(index){
        return wx.setStorageSync('latestIndex', index);
    };
    _getLatest(){
        return wx.getStorageSync('latestIndex');
    };
    _getKey(index){
        return `classic-${index}`;
    }
}

export default ClassicModel;




